<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <el-input v-model="queryWord" placeholder="请输入内容" clearable>
        <el-button
          slot="append"
          icon="el-icon-search"
          @click="getList"
        ></el-button>
      </el-input>
      <el-row>
        <el-button type="primary" @click="dialogFormVisible = true"
          >添加用户</el-button
        >
      </el-row>
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column type="index" width="50"> </el-table-column>
        <el-table-column prop="username" label="姓名" width="188">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="188">
        </el-table-column>
        <el-table-column prop="create_time" label="电话" width="188">
        </el-table-column>
        <el-table-column prop="role_name" label="角色" width="188">
        </el-table-column>
        <el-table-column label="状态" width="232">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @input="situation(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作" width="220">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              @click="edit(scope.row)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="del(scope.row)"
            ></el-button>
            <el-button
              type="warning"
              icon="el-icon-setting"
              @click="assign(scope.row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[2, 4, 6, 8, 10]"
        :page-size="2"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
      <!-- 添加对话框 -->
      <el-dialog title="添加用户" :visible.sync="dialogFormVisible">
        <el-form :model="form" ref="form">
          <el-form-item
            label="用户名"
            :label-width="formLabelWidth"
            prop="name"
            :rules="[
              {
                required: true,
                message: '用户名不能为空',
                trigger: 'blur',
              },
              {
                min: 6,
                message: '用户名至少大于6个字符',
                trigger: 'blur',
              },
            ]"
          >
            <el-input
              v-model="form.name"
              autocomplete="off"
              class="inputWidth"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="密码"
            :label-width="formLabelWidth"
            prop="password"
            :rules="[
              {
                required: true,
                message: '密码不能为空',
                trigger: 'blur',
              },
              {
                min: 6,
                message: '密码至少为6位',
                trigger: 'blur',
              },
            ]"
          >
            <el-input
              v-model="form.password"
              autocomplete="off"
              class="inputWidth"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="邮箱"
            :label-width="formLabelWidth"
            prop="email"
            :rules="[
              {
                message: '请输入邮箱地址',
                trigger: 'blur',
              },
              {
                type: 'email',
                message: '请输入正确的邮箱地址',
                trigger: ['blur', 'change'],
              },
            ]"
          >
            <el-input
              v-model="form.email"
              autocomplete="off"
              class="inputWidth"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="手机"
            :label-width="formLabelWidth"
            prop="phone"
            :rules="[
              {
                message: '手机不能为空',
                trigger: 'blur',
              },
              {
                min: 11,
                max: 11,
                message: '请输入正确的11位手机号',
                trigger: 'blur',
              },
            ]"
          >
            <el-input
              v-model="form.phone"
              autocomplete="off"
              class="inputWidth"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="check('form')">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 修改对话框 -->
      <el-dialog title="修改用户" :visible.sync="dialogFormVisible1">
        <el-form :model="form">
          <el-form-item label="用户名" :label-width="formLabelWidth">
            <el-input
              v-model="form.name"
              autocomplete="off"
              class="inputWidth"
              disabled
            ></el-input>
          </el-form-item>
          <el-form-item
            label="邮箱"
            :label-width="formLabelWidth"
            prop="email"
            :rules="[
              {
                required: true,
                message: '请输入邮箱地址',
                trigger: 'blur',
              },
              {
                type: 'email',
                message: '请输入正确的邮箱地址',
                trigger: ['blur', 'change'],
              },
            ]"
          >
            <el-input
              v-model="form.email"
              autocomplete="off"
              class="inputWidth"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="手机"
            :label-width="formLabelWidth"
            prop="phone"
            :rules="[
              {
                required: true,
                message: '手机不能为空',
                trigger: 'blur',
              },
              {
                min: 11,
                max: 11,
                message: '请输入正确的11位手机号',
                trigger: 'blur',
              },
            ]"
          >
            <el-input
              v-model="form.phone"
              autocomplete="off"
              class="inputWidth"
            ></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible1 = false">取 消</el-button>
          <el-button type="primary" @click="modify">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 分配权限对话框 -->
      <el-dialog title="分配角色" :visible.sync="dialogFormVisible2">
        <el-form :model="form">
          <div class="rowHeight">
            <span>当前的用户：</span>
            <span>{{ form.name }}</span>
          </div>
          <div class="rowHeight">
            <span>当前的角色：</span>
            <span>{{ form.role_name }}</span>
          </div>
          <el-form-item label="分配新角色：" :label-width="widthSecond">
            <el-select v-model="form.region" placeholder="请选择">
              <el-option label="主管" value="主管"></el-option>
              <el-option label="经理" value="经理"></el-option>
              <el-option label="副经理" value="副经理"></el-option>
              <el-option label="组长" value="组长"></el-option>
              <el-option label="副组长" value="副组长"></el-option>
              <el-option label="组员" value="组员"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible2 = false">取 消</el-button>
          <el-button type="primary" @click="assignUpdate">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      input: '',
      tableData: [],
      value1: true,
      currentPage: 1,
      pageCount: 2,
      total: 0,
      queryWord: '',
      dialogFormVisible: false,
      dialogFormVisible1: false,
      dialogFormVisible2: false,
      form: {
        name: '',
        password: '',
        email: '',
        phone: '',
        role_name: '',
      },
      countID: '',
      formLabelWidth: '80px',
      widthSecond: '98px',
      timer: null,
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 用户名校验
    check(form) {
      this.$refs[form].validate(async (valid) => {
        if (valid) {
          let data = await this.$http({
            url: '/users',
            method: 'post',
            data: {
              username: this.form.name,
              password: this.form.password,
              email: this.form.email,
              mobile: this.form.phone,
            },
          })
          this.getList()
          this.dialogFormVisible = false
          this.$message({
            message: '添加用户信息成功！',
            type: 'success',
          })
          this.form.name = ''
          this.form.password = ''
          this.form.email = ''
          this.form.phone = ''
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 删除用户
    del(obj) {
      // 限制admin用户
      if (obj.username == 'admin') {
        this.$message.error('不允许删除admin用户！')
        return
      }
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.$http({
            url: `/users/${obj.id}`,
            method: 'delete',
            data: {
              id: obj.id,
            },
          })
            .then((res) => {
              this.getList()
            })
            .catch((err) => {
              console.log(err)
            })
          this.$message({
            type: 'success',
            message: '删除用户成功！',
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    // 分页器函数
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.pageCount = val
      this.getList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.currentPage = val
      this.getList()
    },
    // 点击编辑
    edit(obj) {
      this.dialogFormVisible1 = true
      this.form.name = obj.username
      this.form.email = obj.email
      this.form.phone = obj.mobile
      this.countID = obj.id
    },
    // 编辑后确认
    modify() {
      this.dialogFormVisible1 = false
      this.$http({
        url: `users/${this.countID}`,
        method: 'put',
        data: {
          id: this.countID,
          email: this.form.email,
          mobile: this.form.phone,
        },
      })
        .then((res) => {
          this.getList()
        })
        .catch((err) => {
          console.log(err)
        })
      this.$message({
        message: '修改用户信息成功！',
        type: 'success',
      })
    },
    // 更新用户状态
    situation(obj) {
      let that = this
      let flag = true
      if (flag) {
        clearTimeout(this.timer)
        this.timer = setTimeout(function () {
          flag = false
          that
            .$http({
              url: `/users/${obj.id}/state/${obj.mg_state}`,
              method: 'put',
            })
            .then((res) => {
              that.getList()
              if (res.status == 200) {
                that.$message({
                  message: '更新用户状态成功！',
                  type: 'success',
                })
              } else {
                that.$message({
                  message: '网络忙,请稍后再试！',
                  type: 'warning',
                })
              }
            })
            .catch((err) => {
              that.$message({
                message: '网络忙,请稍后再试！',
                type: 'danger',
              })
            })
        }, 1800)
      }
    },
    // 分配权限
    assign(obj) {
      this.dialogFormVisible2 = true
      this.form.name = obj.username
      this.form.role_name = obj.role_name
      this.countID = obj.id
      console.log(obj)
    },
    async assignUpdate() {
      let resID = await this.$http({
        url: '/roles',
      })
      let arr = resID.data.data
      // 根据id值查询对应对象
      let obj = arr.find((item) => item.roleName == this.form.region)
      let resdata = await this.$http({
        url: `users/${this.countID}/role`,
        method: 'put',
        data: {
          id: this.countID,
          rid: obj.id,
        },
      })
      this.getList()
      console.log(resdata);
      this.dialogFormVisible2 = false
      this.$message({
        message: '分配用户权限成功！',
        type: 'success',
      })
      return
    },
    // 公共方法
    getList() {
      this.$http({
        url: '/users',
        params: {
          pagenum: this.currentPage,
          pagesize: this.pageCount,
          query: this.queryWord,
        },
      })
        .then((res) => {
          this.tableData = res.data.data.users
          this.total = res.data.data.total
          console.log(res)
        })
        .catch((err) => {
          console.log(err)
        })
    },
  },
}
</script>

<style lang="less" scoped>
.el-input {
  width: 404px;
}
.el-row {
  display: inline-block;
  margin-left: 20px;
}
.el-button {
  padding: 9px 20px;
}
.inputWidth {
  width: 95%;
  height: 45px;
}
.rowHeight {
  height: 30px;
}
</style>
